<template>
  <div>
    <!-- 搜索框+新增+批量删除界面 -->
    <el-form :inline="true">
      <el-form-item>
        <el-input v-model="searchForm.username" placeholder="用户名称" clearable>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="getUserList">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button @click="dialogVisible = true" type="primary" v-if="hasAuth('sys:user:save')">新增</el-button>
      </el-form-item>
      <el-form-item>
        <el-popconfirm title="确定要批量删除吗？" @confirm="delHandle(null)">
          <el-button slot="reference" type="danger" :disabled="delBtlStatu" v-if="hasAuth('sys:user:delete')">彻底删除</el-button>
        </el-popconfirm>
      </el-form-item>
    </el-form>
    <!-- **************************************************************************************************************************************** -->
    <!-- 页面的主题数据显示-->
    <el-table :data="tableData" tooltip-effect="dark" style="width: 100%" border stripe default-expand-all
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="40px">
      </el-table-column>
      <el-table-column  label="头像" width="52px">
        <template slot-scope="scope">
          <el-avatar  :src="scope.row.avatar">
          </el-avatar>
        </template>
      </el-table-column>
      <el-table-column prop="username" label="用户名" width="80px">
      
      </el-table-column>
      <el-table-column prop="code" label="角色名称" width="200px">
        <template slot-scope="scope">
          <el-tag size="samll" type="info" v-for="item in scope.row.sysRoleList">{{ item.name }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="email" label="邮箱" width="100px">
      </el-table-column>
      <el-table-column prpo="phone" label="手机号" width="100px">
      </el-table-column>
      <el-table-column prop="statu" label="状态" width="75px">
        <template slot-scope="scope">
          <el-tag size="small" v-if="scope.row.statu === 1" type="success">正常</el-tag>
          <el-tag size="small" v-else="scope.row.statu === 0" type="danger">禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="created" label="创建时间" show-overflow-tooltip>
      </el-table-column>
      <el-table-column prop="date" label="操作">
        <template slot-scope="scope">
          <el-button type="text" @click="permHandle(scope.row.id)">分配角色</el-button>
          <el-divider direction="vertical"></el-divider>
          <el-button type="text" @click="resetPasswdHandle(scope.row.id,scope.row.username)">重置密码</el-button>
          <el-divider direction="vertical"></el-divider>
          <el-button type="text" @click="editHandle(scope.row.id)">编辑</el-button>
          <el-divider direction="vertical"></el-divider>
          <template>
            <el-popconfirm title="这是一段内容确定删除吗？" @confirm=delHandle(scope.row.id)>
              <el-button slot="reference" type="text"> 删除</el-button>
            </el-popconfirm>
          </template>
        </template>
      </el-table-column>
    </el-table>
    <!-- **************************************************************************************************************************************** -->
    <!--    分页插件-->
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
      layout="total, sizes, prev, pager, next, jumper" :page-sizes="[10, 20, 50, 100]" :current-page="current"
      :page-size="size" :total="total">
    </el-pagination>
    <!-- ******************************************************************************************************************************************** -->
    <!-- 新增或者修改的弹窗界面显示 -->
    <el-dialog title="用户信息" :visible.sync="dialogVisible" width="600px" :before-close="handleClose">
      <el-form :model="editForm" :rules="editFromRules" ref="editForm" label-width="100px" class="demo-editForm">
        <!--        菜单名称-->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" autocomplete="off" ></el-input>
        </el-form-item>
        <!--        权限编码-->
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <!--        图标-->
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="editForm.phone" autocomplete="off"></el-input>
        </el-form-item>
        <!--        状态-->
        <el-form-item label="状态" prop="statu">
          <el-radio-group v-model="editForm.statu">
            <el-radio :label=0>禁用</el-radio>
            <el-radio :label=1>正常</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item style="margin-left: 200px">
          <el-button type="primary" @click="submitForm('editForm')">立即创建</el-button>
          <el-button @click="resetForm('editForm')">重置</el-button>
        </el-form-item>
      </el-form>
      <!--    <el-button @click="dialogVisible = false">取 消</el-button>-->
      <!--    <el-button type="primary" @click="dialogVisible = false">确 定</el-button>-->
    </el-dialog>
    <!-- ****************************************************************************************************************************************** -->
    <!--分配权限  -->
    <el-dialog title="分配权限" :visible.sync="permDialogVisible" width="600px">
      <el-form :model="permForm">
        <el-tree :data="permTreeData" show-checkbox node-key="id" default-expand-all :props="defaultProps" ref="permTree"
          :check-strictly=true>

        </el-tree>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="permDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitPermFormHandle('permForm')">确 定</el-button>
      </span>
    </el-dialog>
    <!-- **************************************************************************************************************************************** -->
  </div>
</template>
<script>
export default {
  name: "User",
  created() {
    debugger
    this.getUserList()
    this.$axios.get('/sys/role/list').then(res => {
      console.log("sys/role/list--------"+res);
      this.permTreeData = res.data.data.records
      console.log("perm----------------"+this.permTreeData)    })

  },
  data() {
    return {
      searchForm: {
        username: ""
      },
      delBtlStatu: true,
      tableData: [],
      size: 10,
      total: 0,
      current: 1,
      dialogVisible: false,
      editForm: {},
      editFromRules: {
        username: [
          { required: true, message: '请选择用户名称', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
        ],
        statu: [
          { required: true, message: '请选择状态', trigger: 'blur' },
        ]
      },
      multipleSelection: [],
      permDialogVisible: false,
      permForm: {

      },
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      permTreeData: []
    }
  },

  methods: {
    handleSelectionChange(val) {
      this.multipleSelection = val;
      this.delBtlStatu = val.length === 0
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.size = val
      this.getUserList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.current = val
      this.getUserList()
    },
    handleClose() {
      this.resetForm('editForm')
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.dialogVisible = false
      this.editForm = {}
    },
    getUserList() {
      this.$axios.get("/sys/user/list", {
        params: {
          name: this.searchForm.username,
          current: this.current,
          size: this.size

        }
      }).then(res => {
        debugger
        console.log(res);
        this.tableData = res.data.data.records

        this.total = res.data.data.total
        this.size = res.data.data.size
        this.current = res.data.data.current
      })


    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$axios.post("/sys/user/" + (this.editForm.id ? "update" : "save"), this.editForm).then(res => {
            this.$message({
              showClose: true,
              message: '恭喜你，操作成功',
              type: 'success',
              onClose: () => {
                 this.getUserList()
              }
            });

          })
          this.resetForm(formName)
          this.dialogVisible = false
        } else {
          this.$message.error('错了哦，这是一条错误消息');
        }
      });
    },
    editHandle(id) {
      // localStorage.setItem("menuId",id)
      this.dialogVisible = true
      //当点击编辑的时候得显示这个弹窗
      this.$axios.get('/sys/user/info/' + id).then(res => {
        // console.log(res)
        this.editForm = res.data.data
      })

    },
    delHandle(id) {
      debugger
      var ids = []
      if (id) {
        ids.push(id)
      } else {
        // this.multipSelection.for(row => ids.push(row.id))
        this.multipleSelection.forEach(row => {
          ids.push(row.id)
        })
      }
      console.log(ids);
      this.$axios.post("/sys/user/delete", ids).then(res => {
        
            this.getUserList()
   
      })
    },
    permHandle(id) {
      debugger
      this.permDialogVisible = true
      this.$axios.get('/sys/user/info/' + id).then(res => {
        this.permForm = res.data.data
        let roleIds =[]
        res.data.data.sysRoleList.forEach(row =>{
          roleIds.push(row.id)
        })
        // debugger
        // console.log(res);
        this.$refs.permTree.setCheckedKeys(roleIds)

        // this.$refs.tree.setCheckedKeys(res.data.data.menuIds)

      })
    },
    submitPermFormHandle(formName) {
      var roleIds = this.$refs.permTree.getCheckedKeys();
      // console.log(menuIds);
      this.$axios.post('/sys/user/role/' + this.permForm.id, roleIds).then(res => {
        this.$message({
          showClose: true,
          message: '恭喜你，操作成功',
          type: 'success',
          onClose: () => {
            this.getUserList()
          }
        });
      })
      this.permDialogVisible = false
    },
    resetPasswdHandle(id,username){
      this.$confirm('将重置用户【'+username+'】的密码，是否继续？','提示',{
        confirmButtonText:'确定',
        cancelButtonText:'取消',
        type:'warning'
      }).then(() =>{
        this.$axios.post('/sys/user/repass',id).then(res => {
          this.$message({
            showClose:true,
            message:"恭喜你操作成功",
            type:'success',
            onClose: () =>{
                console.log("关闭这个项目框"),
                this.getUserList()
            },
            
            
          })
        })
      }).catch(action =>{
        if (action == 'cancel') {
              this.getUserList()
        }


      })
    }
  }
}
</script>
<style scoped>
.el-pagination {
  float: right;
  margin-top: 22px;
  /* //padding-right: 50px; */
}
</style>